/*
Copyright (C) 2007 Nathanael Ness

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
function NowPlaying(call_function)
{
	var me = this;
	var error = null;
	onSongChange = call_function;
  var title_text = "";
  var artist_text = ""
  var album_text = "";
  var info_request = new XMLHttpRequest();
  var update_timer = null;
  var text = null;
	var last_update = "Sat, 1 Jan 2000 00:00:00 GMT";

	this.getTitle = function() {
		return title_text;
	}
	
	this.getArtist = function() {
		return artist_text;
	}
	
	this.getAlbum = function() {
		if(album_text.match(/self ?- ?titled/i) != null) {
			return artist_text;
		} else {
			return album_text;
		}
	}
	
	this.reset = function() {
	  clearInterval(update_timer);
		update_timer = setInterval ( function(){ me.request_update()}, 15000 );
	}
	
  this.request_update = function() {
	//if(system.network != true) {return;}
	try {
	  info_request.open("GET",  "http://www.effectradio.com/effectplaylist.txt", true);
	  info_request.setRequestHeader( "If-Modified-Since", last_update ); 
		last_update = formatDate(new Date(new Date().toUTCString()),'E, d MM yyyy kk:mm:ss') + " GMT";
	} catch (e) {
	  error = "Failed to connect to effectradio.com";
	  info_request = null;
	  return;
	}
	info_request.onreadystatechange = this.recieve_update;
	try {
      info_request.send();
    } catch (e) {
      error = "FAILED B";
      return;
    }
	return;
  }

  this.recieve_update = function() {
	if (info_request.readyState != 4) {
      return null;
	}
	if (info_request.status != 200) {
	error = "State is not 200... this is bad.";
	return null;
	}
	info = info_request.responseText;
	
	if ((info == null) || (info == undefined) || (info == "")) {
		return;
	}
	
	info = info.split('\n');
  text = info[0].split("=");
	if(text[1] == title_text) {
		return;
	}
	title_text = text[1];
  text = info[1].split("=");
	text[1] = text[1].replace(/[\n\r\t]/g,"");
	if(text[1] == "") {
		var temp = info[2].split("&artist=");
		text = temp[0].split("=");
		album_text = text[1];
		artist_text = temp[1];
	} else {
	  artist_text = text[1];
	  text = info[2].split("=");
	  album_text = text[1];
	}
	onSongChange();
	if(update_timer == null) 
		update_timer = setInterval ( function(){ me.request_update()}, 15000 );
  }
}